<?php

namespace app\controller\customer;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use app\common\DataPermissionHelper;
use app\model\customer\Customer as CustomerModel;
use app\model\customer\CustomerContact;
use app\model\contract\Contract;
use app\model\customer\CustomerTrace;
use app\model\system\File;

/**
 * 客户管理控制器
 * 
 * 提供客户列表查询、详情查看、新增、编辑、删除、废弃等功能
 * 
 * @package app\controller\customer
 */
class Customer extends BaseController
{
    /**
     * 无需登录的方法
     * 
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需权限验证的方法
     * 
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 获取客户列表
     * 
     * 支持多条件筛选、分页查询、关键词搜索等功能
     * 
     * @return \think\response\Json
     */
    public function list()
    {
        try {
            $param = Request::param();
            $page = max(1, (int)($param['page'] ?? 1));
            $limit = max(1, min(100, (int)($param['limit'] ?? 10)));

            // 构建查询条件
            $where = $this->buildQueryConditions($param);

            // 获取客户列表
            $customerModel = new CustomerModel();
            $result = $customerModel->getCustomerList($where, $page, $limit);
            
            // 确保分页参数正确应用
            if (empty($result['list'])) {
                return $this->paginate([], 0, $page, $limit, '获取客户列表成功');
            }

            // 严格限制返回数据数量
            $result['list'] = array_slice($result['list'], 0, $limit);
            return $this->paginate($result['list'], $result['total'], $page, $limit, '获取客户列表成功');

        } catch (\Exception $e) {
            return $this->error('获取客户列表失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 查看客户详情
     *
     * @return \think\response\Json
     */
    public function view()
    {
        $id = Request::param('id/d', 0);

        if (empty($id)) {
            return $this->paramError('客户ID不能为空');
        }

        // 检查是否为合同创建流程的特殊请求
        // 通过请求头或特殊参数标识，用于绕过权限检查
        $isContractWorkflow = Request::header('x-contract-workflow') === '1'
            || Request::param('contract_workflow', 0) == 1;

        // 如果不是合同创建流程，则进行常规权限检查
        if (!$isContractWorkflow) {
            // 使用增强版权权检查（集成 oa_data_auth 特殊权限）
            if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $id, [
                'personal' => true,     // 个人数据权限
                'department' => true,   // 部门数据权限
                'shared' => true,       // 共享数据权限
                'approval' => false,    // 客户管理不使用审批权限
                'creator' => true       // 录入人权限 - 允许录入人访问自己录入的数据
            ])) {
                return $this->error('无权访问此客户信息', 403);
            }
        }

        try {
            $customerModel = new CustomerModel();
            $customer = $customerModel->getCustomerDetail($id);

            if (empty($customer)) {
                return $this->error('客户不存在', 404);
            }

            // 将模型对象转换为数组
            $customerArray = $customer instanceof \think\Model ? $customer->toArray() : (array)$customer;

            // 补充关联信息
            $customerArray = $this->enrichCustomerDetail($customerArray);

            return $this->success($customerArray, '获取客户详情成功');

        } catch (\Exception $e) {
            // 记录详细的错误信息到日志
            trace('客户详情API错误 - ID: ' . $id . ', 错误: ' . $e->getMessage(), 'error');
            trace('错误堆栈: ' . $e->getTraceAsString(), 'error');
            
            // 优化错误信息，避免暴露敏感信息
            $userFriendlyMessage = '获取客户详情失败，请稍后重试';
            return $this->error($userFriendlyMessage, 500);
        }
    }

    /**
     * 新增客户
     * 
     * @return \think\response\Json
     */
    public function add()
    {
        $param = Request::param();

        // 数据验证
        $validate = $this->validateCustomerData($param);
        if ($validate !== true) {
            return $this->paramError($validate);
        }

        // 检查创建权限（使用增强版权权检查，包含法务部门和部门负责人权限）
        if (!DataPermissionHelper::checkDataAccessEnhanced('customer', 0, [
            'check_leader' => true
        ])) {
            return $this->error('您没有权限创建客户', 403);
        }

        try {
            // 获取当前登录用户ID，用于设置录入人
            $currentUserId = DataPermissionHelper::getCurrentUserId();
            if ($currentUserId <= 0) {
                $currentUserId = (int)($param['creator_id'] ?? 1); // 备用：使用传入的creator_id或默认为1
            }

            $data = $this->prepareCustomerData($param);
            $customerModel = new CustomerModel();
            $customerId = $customerModel->addCustomer($data);

            // 处理联系人信息
            $contactData = [
                'cid' => $customerId,
                'name' => $param['contact_name'] ?? '',
                'mobile' => $param['contact_mobile'] ?? '',
                'sex' => $param['contact_gender'] ?? 0,
                'email' => $param['contact_email'] ?? '',
                'qq' => $param['contact_qq'] ?? '',
                'wechat' => $param['contact_wechat'] ?? '',
                'is_default' => $param['is_primary'] ?? 1,
                'admin_id' => $currentUserId // 使用当前用户ID
            ];

            // 只有当联系人姓名和手机号至少有一个存在时，才添加联系人
            if (!empty($contactData['name']) || !empty($contactData['mobile'])) {
                $contactModel = new CustomerContact();
                $contactModel->addContact($contactData);
            }

            return $this->success(['id' => $customerId], '客户创建成功');

        } catch (\Exception $e) {
            return $this->error('创建客户失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 编辑客户
     * 
     * @return \think\response\Json
     */
    public function edit()
    {
        $param = Request::param();
        $id = $param['id'] ?? 0;

        if (empty($id)) {
            return $this->paramError('客户ID不能为空');
        }

        // 数据验证
        $validate = $this->validateCustomerData($param);
        if ($validate !== true) {
            return $this->paramError($validate);
        }

        // 检查数据权限
        if (!DataPermissionHelper::checkDataAccess('customer', $id)) {
            return $this->error('无权编辑此客户信息', 403);
        }

        try {
            // 获取当前登录用户ID，用于设置录入人
            $currentUserId = DataPermissionHelper::getCurrentUserId();
            if ($currentUserId <= 0) {
                $currentUserId = (int)($param['creator_id'] ?? 1); // 备用：使用传入的creator_id或默认为1
            }

            $data = $this->prepareCustomerData($param, true);
            $customerModel = new CustomerModel();
            $customerModel->updateCustomer($id, $data);

            // 处理联系人信息
            $contactName = $param['contact_name'] ?? '';
            $contactMobile = $param['contact_mobile'] ?? '';

            // 只有当联系人姓名和手机号至少有一个存在时，才处理联系人信息
            if (!empty($contactName) || !empty($contactMobile)) {
                $contactModel = new CustomerContact();

                // 判断联系人表中是否已经存在提交的联系人信息
                $existingContact = $contactModel->where('cid', $id)
                    ->where('name', $contactName)
                    ->where('mobile', $contactMobile)
                    ->where('delete_time', 0)
                    ->find();

                // 如果联系人不存在，新增联系人记录
                if (empty($existingContact)) {
                    // 检查是否存在默认联系人
                    $hasDefaultContact = $contactModel->where('cid', $id)
                        ->where('is_default', 1)
                        ->where('delete_time', 0)
                        ->count() > 0;

                    // 如果没有默认联系人，则设为默认；否则不设为默认
                    $isDefault = !$hasDefaultContact ? 1 : 0;

                    $contactData = [
                        'cid' => $id,
                        'name' => $contactName,
                        'mobile' => $contactMobile,
                        'sex' => $param['contact_gender'] ?? 0,
                        'email' => $param['contact_email'] ?? '',
                        'qq' => $param['contact_qq'] ?? '',
                        'wechat' => $param['contact_wechat'] ?? '',
                        'is_default' => $isDefault,
                        'admin_id' => $currentUserId // 使用当前用户ID
                    ];
                    
                    $contactModel->addContact($contactData);
                    
                    // 如果设置为默认联系人，需要将其他联系人设为非默认
                    if ($isDefault == 1 && $hasDefaultContact) {
                        $contactModel->where('cid', $id)
                            ->where('name', '<>', $contactName)
                            ->where('mobile', '<>', $contactMobile)
                            ->update(['is_default' => 0]);
                    }
                }
            }

            return $this->success(['id' => $id], '客户更新成功');

        } catch (\Exception $e) {
            return $this->error('更新客户失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 删除客户（软删除）
     * 
     * @return \think\response\Json
     */
    public function del()
    {
        $id = Request::param('id/d', 0);

        if (empty($id)) {
            return $this->paramError('客户ID不能为空');
        }

        // 检查数据权限
        if (!DataPermissionHelper::checkDataAccess('customer', $id)) {
            return $this->error('无权删除此客户信息', 403);
        }

        try {
            $customerModel = new CustomerModel();
            $customerModel->softDeleteCustomer($id);

            return $this->success(['id' => $id], '客户删除成功');

        } catch (\Exception $e) {
            return $this->error('删除客户失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 废弃/恢复客户
     * 
     * @return \think\response\Json
     */
    public function discard()
    {
        $id = Request::param('id/d', 0);
        $isDiscard = Request::param('is_discard/d', 1);

        if (empty($id)) {
            return $this->paramError('客户ID不能为空');
        }

        // 检查数据权限
        if (!DataPermissionHelper::checkDataAccess('customer', $id)) {
            return $this->error('无权操作此客户', 403);
        }

        try {
            $customerModel = new CustomerModel();
            
            if ($isDiscard == 0) {
                $customerModel->discardCustomer($id, false);
                return $this->success(['id' => $id], '客户恢复成功');
            } else {
                $customerModel->discardCustomer($id, true);
                return $this->success(['id' => $id], '客户废弃成功');
            }

        } catch (\Exception $e) {
            return $this->error('操作失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 从客户快速创建当事人
     * 
     * @return \think\response\Json
     */
    public function createPartyFromCustomer()
    {
        $customerId = Request::param('customer_id/d', 0);

        if (empty($customerId)) {
            return $this->paramError('客户ID不能为空');
        }

        try {
            $customerModel = new CustomerModel();
            $customer = $customerModel->getCustomerById($customerId);

            if (empty($customer)) {
                return $this->error('客户不存在', 404);
            }

            // 使用Party模型检查是否已创建当事人
            $existingParty = \app\model\lawcase\Party::getPartyByCustomerId($customerId);

            if (!empty($existingParty)) {
                return $this->error('该客户已创建当事人', 400);
            }

            // 使用Party模型创建当事人
            $partyId = \app\model\lawcase\Party::createPartyFromCustomer($customer);

            if ($partyId === false) {
                return $this->error('创建当事人失败', 500);
            }

            return $this->success(['id' => $partyId], '创建当事人成功');

        } catch (\Exception $e) {
            return $this->error('创建当事人失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 搜索客户
     * 
     * @return \think\response\Json
     */
    public function search()
    {
        $keyword = Request::param('keyword', '');
        
        if (empty($keyword)) {
            return $this->error('搜索关键词不能为空', 400);
        }

        try {
            $customerModel = new CustomerModel();
            $results = $customerModel->searchCustomers($keyword);
            
            return $this->success($results, '搜索成功');
        } catch (\Exception $e) {
            return $this->error('搜索失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 构建查询条件
     * 
     * @param array $param 请求参数
     * @return array 查询条件
     */
    private function buildQueryConditions(array $param): array
    {
        $where = [];
        $where[] = ['c.delete_time', '=', 0];
        
        // 根据is_discard参数动态设置废弃状态查询条件
        $isDiscard = $param['is_discard'] ?? null;
        if ($isDiscard === '1' || $isDiscard === 1) {
            // 查询废弃的客户（discard_time不为0）
            $where[] = ['c.discard_time', '>', 0];
        } else {
            // 默认查询未废弃的客户（discard_time为0）
            $where[] = ['c.discard_time', '=', 0];
        }

        // 基础字段筛选
        if (!empty($param['admin_id'])) {
            $where[] = ['c.belong_uid', '=', $param['admin_id']];
        }

        // 其他筛选条件
        $filters = [
            'grade_id', 'source_id', 'industry_id', 
            'customer_type', 'customer_status',
            'group_code', 'is_primary' // 添加对group_code和is_primary的支持
        ];

        foreach ($filters as $field) {
            // 特殊处理is_primary字段，因为0也是有效值
            if ($field === 'is_primary' && array_key_exists($field, $param)) {
                $where[] = ['c.' . $field, '=', $param[$field]];
            } else if (!empty($param[$field])) {
                $where[] = ['c.' . $field, '=', $param[$field]];
            }
        }

        // 关键词搜索（支持 keyword 或 keywords 参数）
        if (!empty($param['keyword'])) {
            $this->applyKeywordSearch($where, $param['keyword']);
        } elseif (!empty($param['keywords'])) {
            $this->applyKeywordSearch($where, $param['keywords']);
        }

        // 合同金额筛选
        if (!empty($param['min_amount']) || !empty($param['max_amount'])) {
            $this->applyContractAmountFilter($where, $param);
        }

        // 时间范围筛选
        $this->applyTimeRangeFilters($where, $param);

        // 应用数据权限控制 - 与详情页使用相同的权限检查逻辑
        // 确保能看到客户列表的用户也有权限查看客户详情
        $where = DataPermissionHelper::buildComprehensiveDataWhere($where, [
            'personal' => true,     // 个人数据权限
            'department' => true,   // 部门数据权限
            'shared' => true,       // 共享数据权限
            'approval' => false     // 客户管理不使用审批权限
        ]);

        return $where; // 返回包含权限控制的查询条件
    }

    /**
     * 应用关键词搜索
     * 
     * @param array $where 查询条件
     * @param string $keywords 关键词
     */
    private function applyKeywordSearch(array &$where, string $keywords): void
    {
        $customerModel = new CustomerModel();
        $customerIds = $customerModel->searchCustomerIdsByKeywords(trim($keywords), $where);

        if (!empty($customerIds)) {
            $where[] = ['c.id', 'in', $customerIds];
        } else {
            $where[] = ['c.id', '=', 0];
        }
    }

    /**
     * 应用合同金额筛选
     * 
     * @param array $where 查询条件
     * @param array $param 请求参数
     */
    private function applyContractAmountFilter(array &$where, array $param): void
    {
        $contractModel = new Contract();
        $customerIds = $contractModel->getCustomerIdsByAmountRange(
            $param['min_amount'] ?? 0,
            $param['max_amount'] ?? 0
        );

        if (!empty($customerIds)) {
            $where[] = ['c.id', 'in', $customerIds];
        } else {
            $where[] = ['c.id', '=', 0];
        }
    }

    /**
     * 应用时间范围筛选
     * 
     * @param array $where 查询条件
     * @param array $param 请求参数
     */
    private function applyTimeRangeFilters(array &$where, array $param): void
    {
        $timeFields = [
            'next_time' => 'c.next_time',
            'follow_time' => 'c.follow_time',
            'start_discard_time' => 'c.discard_time',
            'end_discard_time' => 'c.discard_time'
        ];

        foreach ($timeFields as $paramKey => $field) {
            if (!empty($param[$paramKey])) {
                $this->parseTimeRange($param[$paramKey], $field, $where, $paramKey);
            }
        }
    }

    /**
     * 解析时间范围
     * 
     * @param string $timeRange 时间范围
     * @param string $field 字段名
     * @param array $where 查询条件
     * @param string $paramKey 参数键名
     */
    private function parseTimeRange(string $timeRange, string $field, array &$where, string $paramKey): void
    {
        $dates = explode('~', $timeRange);
        if (count($dates) !== 2) {
            return;
        }

        $startTime = strtotime(urldecode($dates[0]));
        $endTime = strtotime(urldecode($dates[1]) . ' 23:59:59');

        if ($startTime === false || $endTime === false) {
            return;
        }

        if (strpos($paramKey, 'start_') === 0) {
            $where[] = [$field, '>=', $startTime];
        } elseif (strpos($paramKey, 'end_') === 0) {
            $where[] = [$field, '<=', $endTime];
        } else {
            $where[] = [$field, 'between', [$startTime, $endTime]];
        }
    }

    /**
     * 丰富客户数据
     * 
     * @param array $customers 客户原始数据
     * @return array 丰富后的数据
     */
    private function enrichCustomerData(array $customers): array
    {
        if (empty($customers)) {
            return [];
        }

        $customerIds = array_column($customers, 'id');

        // 获取联系人信息
        $contactMap = $this->getCustomerContacts($customers);

        // 获取合同统计
        $contractStats = $this->getContractStatistics($customerIds);

        // 组装数据
        return $this->assembleCustomerList($customers, $contactMap, $contractStats);
    }

    /**
     * 获取客户联系人信息
     * 
     * @param array $customers 客户数据
     * @return array 联系人映射
     */
    private function getCustomerContacts(array $customers): array
    {
        $contactMap = [];
        
        // 获取默认联系人
        $contactFirstIds = array_filter(array_column($customers, 'contact_first'));
        if (!empty($contactFirstIds)) {
            $contactModel = new CustomerContact();
            $contacts = $contactModel->getContactsByIds($contactFirstIds);
            foreach ($contacts as $contact) {
                $contactMap[$contact['id']] = $contact;
            }
        }

        // 获取备用联系人
        $customersWithoutContact = [];
        foreach ($customers as $customer) {
            if (empty($customer['contact_first']) || !isset($contactMap[$customer['contact_first']])) {
                $customersWithoutContact[] = $customer['id'];
            }
        }

        if (!empty($customersWithoutContact)) {
            $contactModel = new CustomerContact();
            $backupContacts = $contactModel->getFirstContactsByCustomerIds($customersWithoutContact);
            foreach ($backupContacts as $customerId => $contact) {
                $contactMap['backup_' . $customerId] = $contact;
            }
        }

        return $contactMap;
    }

    /**
     * 获取合同统计数据
     * 
     * @param array $customerIds 客户ID数组
     * @return array 合同统计
     */
    private function getContractStatistics(array $customerIds): array
    {
        $contractModel = new Contract();
        return $contractModel->getContractStatsByCustomerIds($customerIds);
    }

    /**
     * 组装客户列表数据
     * 
     * @param array $customers 客户数据
     * @param array $contactMap 联系人映射
     * @param array $contractStats 合同统计
     * @return array 组装后的数据
     */
    private function assembleCustomerList(array $customers, array $contactMap, array $contractStats): array
    {
        $list = [];

        foreach ($customers as $customer) {
            // 标准化时间字段
            $customer['create_time'] = (int)$customer['create_time'];
            $customer['follow_time'] = (int)$customer['follow_time'];
            $customer['next_time'] = (int)$customer['next_time'];
            $customer['belong_time'] = (int)$customer['belong_time'];
            $customer['discard_time'] = (int)($customer['discard_time'] ?? 0);

            // 设置联系人信息
            $this->setCustomerContactInfo($customer, $contactMap);

            // 设置合同信息
            $this->setCustomerContractInfo($customer, $contractStats);

            $list[] = $customer;
        }

        return $list;
    }

    /**
     * 设置客户联系人信息
     * 
     * @param array &$customer 客户数据
     * @param array $contactMap 联系人映射
     */
    private function setCustomerContactInfo(array &$customer, array $contactMap): void
    {
        $contactName = '';
        $contactMobile = '';

        if (!empty($customer['contact_first']) && isset($contactMap[$customer['contact_first']])) {
            $contact = $contactMap[$customer['contact_first']];
            $contactName = $contact['name'] ?? '';
            $contactMobile = $contact['mobile'] ?? '';
        } elseif (isset($contactMap['backup_' . $customer['id']])) {
            $contact = $contactMap['backup_' . $customer['id']];
            $contactName = $contact['name'] ?? '';
            $contactMobile = $contact['mobile'] ?? '';
        }

        $customer['contact_name'] = $contactName;
        $customer['contact_mobile'] = $contactMobile;
    }

    /**
     * 设置客户合同信息
     * 
     * @param array &$customer 客户数据
     * @param array $contractStats 合同统计
     */
    private function setCustomerContractInfo(array &$customer, array $contractStats): void
    {
        if (isset($contractStats[$customer['id']])) {
            $customer['contract_num'] = (int)($contractStats[$customer['id']]['contract_num'] ?? 0);
            $customer['contract_amount'] = (float)($contractStats[$customer['id']]['contract_amount'] ?? 0);
        } else {
            $customer['contract_num'] = 0;
            $customer['contract_amount'] = 0.0;
        }
    }

    /**
     * 丰富客户详情数据
     * 
     * @param array $customer 客户数据
     * @return array 丰富后的数据
     */
    private function enrichCustomerDetail(array $customer): array
    {
        $customerId = $customer['id'];

        try {
            // 获取默认联系人
            $contactModel = new CustomerContact();
            $contact = $contactModel->getDefaultContactByCustomerId($customerId);
            if ($contact) {
                $customer['contact_name'] = $contact['name'];
                $customer['contact_mobile'] = $contact['mobile'];
            }
        } catch (\Exception $e) {
            trace('获取客户联系人信息失败 - ID: ' . $customerId . ', 错误: ' . $e->getMessage(), 'error');
            // 即使获取联系人失败，也继续执行，不影响主数据
        }

        try {
            // 获取合同统计
            $contractModel = new Contract();
            $contractStats = $contractModel->getContractStatsByCustomerIds([$customerId]);
            $stats = $contractStats[$customerId] ?? ['contract_num' => 0, 'contract_amount' => 0];
            $customer['contract_num'] = (int)$stats['contract_num'];
            $customer['contract_amount'] = (float)$stats['contract_amount'];
        } catch (\Exception $e) {
            trace('获取合同统计信息失败 - ID: ' . $customerId . ', 错误: ' . $e->getMessage(), 'error');
            // 设置默认值
            $customer['contract_num'] = 0;
            $customer['contract_amount'] = 0.0;
        }

        try {
            // 获取附件信息
            $customer['files'] = $this->getCustomerFiles($customerId);
        } catch (\Exception $e) {
            trace('获取客户附件信息失败 - ID: ' . $customerId . ', 错误: ' . $e->getMessage(), 'error');
            // 设置默认值
            $customer['files'] = [];
        }

        try {
            // 获取最新跟进记录
            $traceModel = new CustomerTrace();
            $latestTrace = $traceModel->getLatestTracesByCustomerId($customerId, 1);
            $customer['latest_trace'] = !empty($latestTrace) ? $latestTrace[0] : null;
        } catch (\Exception $e) {
            trace('获取跟进记录失败 - ID: ' . $customerId . ', 错误: ' . $e->getMessage(), 'error');
            // 设置默认值
            $customer['latest_trace'] = null;
        }

        try {
            // 获取客户等级、来源、管家、录入人等关联信息
            $detailedCustomer = Db::name('customer')
                ->alias('c')
                ->where('c.id', $customerId)
                ->join('oa_customer_grade g', 'c.grade_id = g.id', 'LEFT')
                ->join('oa_customer_source s', 'c.source_id = s.id', 'LEFT')
                ->join('oa_admin a', 'c.belong_uid = a.id', 'LEFT')
                // 增加admin_id字段的连接，获取录入人名称
                ->join('oa_admin a2', 'c.admin_id = a2.id', 'LEFT')
                ->field('g.title as grade_name, s.title as source_name, a.name as belong_name, a2.name as creator_name')
                ->find();
            
            if ($detailedCustomer) {
                $customer['grade_name'] = $detailedCustomer['grade_name'] ?? '未设置';
                $customer['source_name'] = $detailedCustomer['source_name'] ?? '未设置';
                $customer['belong_name'] = $detailedCustomer['belong_name'] ?? '未设置';
                $customer['creator_name'] = $detailedCustomer['creator_name'] ?? '未设置';
            } else {
                $customer['grade_name'] = '未设置';
                $customer['source_name'] = '未设置';
                $customer['belong_name'] = '未设置';
            }
        } catch (\Exception $e) {
            trace('获取客户关联信息失败 - ID: ' . $customerId . ', 错误: ' . $e->getMessage(), 'error');
            // 设置默认值
            $customer['grade_name'] = '未设置';
            $customer['source_name'] = '未设置';
            $customer['belong_name'] = '未设置';
        }

        try {
            // 获取会员状态名称
            $statusConfig = Db::name('basic_customer')
                ->where('types', '1')
                ->column('title', 'id');
            $customer['customer_status_name'] = $statusConfig[$customer['customer_status'] ?? 0] ?? '未设置';
        } catch (\Exception $e) {
            trace('获取会员状态信息失败 - ID: ' . $customerId . ', 错误: ' . $e->getMessage(), 'error');
            // 设置默认值
            $customer['customer_status_name'] = '未设置';
        }

        try {
            // 获取地区信息
            $province_name = '';
            $city_name = '';
            $district_name = '';
            
            if (!empty($customer['provinceid'])) {
                $province_name = Db::name('region')->where('id', $customer['provinceid'])->value('name') ?? '';
            }
            if (!empty($customer['cityid'])) {
                $city_name = Db::name('region')->where('id', $customer['cityid'])->value('name') ?? '';
            }
            if (!empty($customer['distid'])) {
                $district_name = Db::name('region')->where('id', $customer['distid'])->value('name') ?? '';
            }
            
            $customer['province_name'] = $province_name;
            $customer['city_name'] = $city_name;
            $customer['district_name'] = $district_name;
        } catch (\Exception $e) {
            trace('获取地区信息失败 - ID: ' . $customerId . ', 错误: ' . $e->getMessage(), 'error');
            // 设置默认值
            $customer['province_name'] = '';
            $customer['city_name'] = '';
            $customer['district_name'] = '';
        }

        return $customer;
    }

    /**
     * 获取客户附件信息
     * 
     * @param int $customerId 客户ID
     * @return array 附件信息
     */
    private function getCustomerFiles(int $customerId): array
    {
        return \app\model\customer\CustomerFile::getCustomerFiles($customerId);
    }

    /**
     * 验证客户数据
     * 
     * @param array $param 请求参数
     * @return true|string 验证结果或错误信息
     */
    private function validateCustomerData(array $param)
    {
        if (empty($param['name'])) {
            return '客户名称不能为空';
        }

        if (strlen($param['name']) > 100) {
            return '客户名称不能超过100个字符';
        }

        // 验证分组代码
        if (isset($param['group_code']) && strlen($param['group_code']) > 50) {
            return '分组代码不能超过50个字符';
        }

        // 验证负责人姓名
        if (isset($param['controller_name']) && strlen($param['controller_name']) > 50) {
            return '负责人姓名不能超过50个字符';
        }

        // 验证关系描述
        if (isset($param['relation_desc']) && strlen($param['relation_desc']) > 200) {
            return '关系描述不能超过200个字符';
        }

        // 验证是否主要客户
        if (isset($param['is_primary']) && !in_array($param['is_primary'], [0, 1])) {
            return '是否主要客户只能是0或1';
        }

        return true;
    }

    /**
     * 准备客户数据
     * 
     * @param array $param 请求参数
     * @param bool $isUpdate 是否为更新操作
     * @return array 处理后的数据
     */
    /**
     * 生成唯一的客户组编码，基于customer_type、name和source_id
     * 
     * @param int $customerType 客户类型
     * @param string $customerName 客户名称
     * @param int $sourceId 客户来源ID
     * @return string 生成的组编码
     */
    private function generateUniqueGroupCode(int $customerType, string $customerName, int $sourceId): string
    {
        // 生成格式：C+客户类型+客户名称首字母+来源ID+年月日时分秒+2位随机数
        $prefix = 'C';
        
        // 客户类型（2位）
        $typeStr = str_pad(strval($customerType), 2, '0', STR_PAD_LEFT);
        
        // 客户名称首字母（2位）
        $nameInitial = '';
        if (!empty($customerName)) {
            // 获取中文字符的拼音首字母或直接取英文首字母
            $firstChar = mb_substr($customerName, 0, 1, 'UTF-8');
            // 判断是否为中文字符
            if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $firstChar)) {
                // 对于中文，我们简化处理，使用固定字符"CN"
                $nameInitial = 'CN';
            } else {
                // 对于英文，取大写首字母
                $nameInitial = strtoupper(substr($firstChar, 0, 1)) . 'N';
            }
        } else {
            $nameInitial = 'NN';
        }
        
        // 来源ID（2位）
        $sourceStr = str_pad(strval($sourceId), 2, '0', STR_PAD_LEFT);
        
        // 时间戳和随机数
        $timestamp = date('YmdHis');
        $random = str_pad(mt_rand(0, 99), 2, '0', STR_PAD_LEFT);
        
        // 组合所有因子生成组编码
        $groupCode = $prefix . $typeStr . $nameInitial . $sourceStr . $timestamp . $random;
        
        // 验证生成的编码是否唯一
        $customerModel = new \app\model\customer\Customer();
        $exists = $customerModel->where('group_code', $groupCode)->find();
        
        // 如果已存在，则重新生成
        if ($exists) {
            return $this->generateUniqueGroupCode($customerType, $customerName, $sourceId);
        }
        
        return $groupCode;
    }
    
    private function prepareCustomerData(array $param, bool $isUpdate = false): array
    {
        // 获取传入的参数
        $groupCode = trim($param['group_code'] ?? '');
        $customerType = (int)($param['customer_type'] ?? 1);
        $customerName = trim($param['name'] ?? '');
        $sourceId = (int)($param['source_id'] ?? 0);

        // 获取当前登录用户信息
        $currentUserId = DataPermissionHelper::getCurrentUserId();
        $currentUserInfo = DataPermissionHelper::getCurrentUserInfo();
        $currentDeptId = $currentUserInfo['department_id'] ?? 0;

        // 如果当前用户ID为0，尝试从参数中获取或使用默认值
        if ($currentUserId <= 0) {
            $currentUserId = (int)($param['admin_id'] ?? 1); // 使用传入的admin_id或默认为1
        }
        
        // 如果是新增操作且没有传入group_code，则自动生成
        if (!$isUpdate && empty($groupCode)) {
            $groupCode = $this->generateUniqueGroupCode($customerType, $customerName, $sourceId);
        }
        
        $data = [
            'customer_type' => (int)($param['customer_type'] ?? 1),
            'name' => trim($param['name']),
            'source_id' => (int)($param['source_id'] ?? 0),
            'grade_id' => (int)($param['grade_id'] ?? 0),
            'industry_id' => (int)($param['industry_id'] ?? 0),
            'services_id' => (int)($param['services_id'] ?? 0),
            'provinceid' => (int)($param['provinceid'] ?? 0),
            'cityid' => (int)($param['cityid'] ?? 0),
            'distid' => (int)($param['distid'] ?? 0),
            'townid' => (int)($param['townid'] ?? 0),
            'address' => trim($param['address'] ?? ''),
            'customer_status' => (int)($param['customer_status'] ?? 0),
            'belong_uid' => (int)($param['belong_uid'] ?? $currentUserId),
            'belong_did' => (int)($param['belong_did'] ?? $currentDeptId),
            'share_ids' => trim($param['share_ids'] ?? ''),
            'content' => trim($param['content'] ?? ''),
            'market' => trim($param['market'] ?? ''),
            'remark' => trim($param['remark'] ?? ''),
            'tax_bank' => trim($param['tax_bank'] ?? ''),
            'tax_banksn' => trim($param['tax_banksn'] ?? ''),
            'tax_num' => trim($param['tax_num'] ?? ''),
            'tax_mobile' => trim($param['tax_mobile'] ?? ''),
            'tax_address' => trim($param['tax_address'] ?? ''),
            'group_code' => $groupCode,
            'is_primary' => (int)($param['is_primary'] ?? 0),
            'controller_name' => trim($param['controller_name'] ?? ''),
            'relation_desc' => trim($param['relation_desc'] ?? ''),
            'update_time' => time()
        ];

        if (!$isUpdate) {
            // 新增时添加的字段
            $data['admin_id'] = $currentUserId; // 使用当前登录用户ID
            $data['belong_time'] = time();
            $data['distribute_time'] = time();
            $data['create_time'] = time();
        }

        return $data;
    }

    /**
     * 获取客户状态选项
     * 
     * 用于前端下拉选择框，提供客户状态的可选项
     * 
     * @return \think\response\Json
     */
    public function status()
    {
        try {
            // 客户状态选项
            $customerStatusOptions = [
                ['value' => 0, 'label' => '未联系'],
                ['value' => 1, 'label' => '已联系'],
                ['value' => 2, 'label' => '有意向'],
                ['value' => 3, 'label' => '已签约'],
                ['value' => 4, 'label' => '已流失'],
                ['value' => 5, 'label' => '已废弃']
            ];

            // 意向状态选项
            $intentStatusOptions = [
                ['value' => 0, 'label' => '未评估'],
                ['value' => 1, 'label' => '低意向'],
                ['value' => 2, 'label' => '中意向'],
                ['value' => 3, 'label' => '高意向'],
                ['value' => 4, 'label' => '已成交']
            ];

            // 客户类型选项
            $customerTypeOptions = [
                ['value' => 16, 'label' => '企业客户'],
                ['value' => 15, 'label' => '个人客户']
            ];

            return $this->success([
                'customer_status' => $customerStatusOptions,
                'customer_type' => $customerTypeOptions
            ], '获取客户状态选项成功');

        } catch (\Exception $e) {
            return $this->error('获取客户状态选项失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取客户基础数据（字典类型数据）
     * @return \think\response\Json
     * @desc 从oa_basic_customer表获取指定类型的字典数据，用于前端下拉选择控件
     * @param int $type 字典类型编码（必须通过请求参数传递）
     * @example GET /api/customer/customer/basic_data?type=1 获取客户状态字典（会员/非会员/过期会员）
     * @example GET /api/customer/customer/basic_data?type=3 获取客户来源字典（电话/微信/上门等）
     * @example GET /api/customer/customer/basic_data?type=5 获取客户类型字典（个人客户/企业客户）
     * @returns 成功返回格式：{"code":0,"msg":"success","data":[{"id":2,"name":"会员"},{"id":3,"name":"非会员"}]}
     * @note 当数据库查询失败或没有数据时，前端应使用本地缓存的默认选项
     */
    public function getCustomerBasicData()
    {
        $type = Request::param('type/d', 1);
        
        try {
            // 验证参数有效性
            if (!is_numeric($type) || $type <= 0) {
                return $this->error('类型参数无效', 400);
            }
            
            $basicModel = new \app\model\customer\Basic();
            $list = $basicModel->getByType($type);
            
            // 确保返回的数据格式正确
            if (empty($list)) {
                return $this->success([], '暂无数据');
            }
            
            return $this->success($list, '获取成功');
        } catch (\Exception $e) {
            // 记录错误日志，但不向前端暴露详细错误信息
            \think\facade\Log::error('获取客户基础数据异常: ' . $e->getMessage());
            return $this->error('获取客户基础数据失败', 500);
        }
    }

    /**
     * 获取基础数据选项
     *
     * 返回用户选项、客户来源等前端下拉选择控件数据
     *
     * @return \think\response\Json
     */
    public function basic_data()
    {
        try {
            // 获取管家列表
            $userOptions = Db::name('admin')
                ->where('status', 1)
                ->where('delete_time', 0)
                ->field('id, name')
                ->select()
                ->toArray();

            $userOptions = array_map(function($item) {
                return ['value' => $item['id'], 'label' => $item['name']];
            }, $userOptions);

            // 获取客户来源
            $sourceOptions = Db::name('customer_source')
                ->where('delete_time', 0)
                ->field('id, title')
                ->select()
                ->toArray();

            $sourceOptions = array_map(function($item) {
                return ['value' => (string)$item['id'], 'label' => $item['title']];
            }, $sourceOptions);

            // 获取客户等级
            $gradeOptions = Db::name('customer_grade')
                ->where('delete_time', 0)
                ->field('id, title')
                ->select()
                ->toArray();

            $gradeOptions = array_map(function($item) {
                return ['value' => (int)$item['id'], 'label' => $item['title']];
            }, $gradeOptions);

            return $this->success([
                'user_options' => $userOptions,
                'source_options' => $sourceOptions,
                'grade_options' => $gradeOptions,
                'dept_options' => [],
                'industry_options' => [],
                'scale_options' => []
            ], '获取成功');

        } catch (\Exception $e) {
            \think\facade\Log::error('获取基础数据异常: ' . $e->getMessage());
            return $this->error('获取基础数据失败', 500);
        }
    }

    /**
     * 获取客户统计信息
     *
     * 返回客户总数、有效客户数、合作客户数等统计数据
     *
     * @return \think\response\Json
     */
    public function statistics()
    {
        try {
            $customerModel = new CustomerModel();

            // 构建基础查询条件
            $baseWhere = [
                ['delete_time', '=', 0],
                ['discard_time', '=', 0]
            ];

            $total = $customerModel->where($baseWhere)->count();

            // 有效客户
            $activeWhere = array_merge($baseWhere, [
                ['customer_status', 'in', [1, 2, 3]]
            ]);
            $active = $customerModel->where($activeWhere)->count();

            // 合作客户
            $cooperationWhere = array_merge($baseWhere, [
                ['customer_status', '=', 4]
            ]);
            $cooperation = $customerModel->where($cooperationWhere)->count();

            // 待跟进
            $toFollowWhere = array_merge($baseWhere, [
                ['next_time', '>', 0],
                ['next_time', '<=', time() + 7*86400]
            ]);
            $toFollow = $customerModel->where($toFollowWhere)->count();

            // 超期未跟进
            $overdueWhere = array_merge($baseWhere, [
                ['follow_time', '>', 0],
                ['follow_time', '<', time() - 7*86400]
            ]);
            $overdue = $customerModel->where($overdueWhere)->count();

            // 计算转化率
            $conversionRate = $total > 0 ? round($cooperation / $total * 100, 2) : 0;

            // 会员客户（有效法务套餐客户）
            $memberCustomers = Db::name('contract')
                ->where('cate_id', 'in', [1, 2, 10, 13]) // 法务套餐类型ID
                ->where('end_time', '>', time())
                ->where('delete_time', 0)
                ->group('customer_id')
                ->column('customer_id');

            // 合同客户
            $contractCustomers = Db::name('contract')
                ->where('customer_id', 'in', function($query) use ($baseWhere) {
                    $query->table('oa_customer')->where($baseWhere)->field('id');
                })
                ->where('delete_time', 0)
                ->group('customer_id')
                ->column('customer_id');

            // 案件客户
            $caseCustomers = Db::name('lawcase')
                ->where('cid', 'in', function($query) use ($baseWhere) {
                    $query->table('oa_customer')->where($baseWhere)->field('id');
                })
                ->where('delete_time', 0)
                ->group('cid')
                ->column('cid');

            return $this->success([
                'total' => $total,
                'active' => $active,
                'cooperation' => $cooperation,
                'to_follow' => $toFollow,
                'overdue' => $overdue,
                'conversion_rate' => $conversionRate,
                'member_customers' => count($memberCustomers),
                'contract_customers' => count($contractCustomers),
                'case_customers' => count($caseCustomers)
            ], '获取统计信息成功');

        } catch (\Exception $e) {
            return $this->error('获取统计信息失败: ' . $e->getMessage(), 500);
        }
    }

    // ============================================
    // 客户联系人管理 API
    // ============================================

    /**
     * 添加客户联系人
     */
    public function addContact()
    {
        $customerId = Request::param('customer_id/d', 0);
        $param = Request::param();

        if (empty($customerId)) {
            return $this->paramError('客户ID不能为空');
        }

        // 检查客户是否存在
        $customer = Db::name('customer')->where('id', $customerId)->where('delete_time', 0)->find();
        if (!$customer) {
            return $this->error('客户不存在', 404);
        }

        // 检查权限
        if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $customerId, [
            'personal' => true,
            'department' => true,
            'shared' => true,
            'approval' => false,
            'creator' => true
        ])) {
            return $this->error('无权操作此客户', 403);
        }

        try {
            $customerModel = new CustomerModel();
            $contactId = $customerModel->addCustomerContact($customerId, $param);

            return $this->success(['id' => $contactId], '添加联系人成功');
        } catch (\Exception $e) {
            return $this->error('添加联系人失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 更新客户联系人
     */
    public function updateContact()
    {
        $contactId = Request::param('id/d', 0);
        $param = Request::param();

        if (empty($contactId)) {
            return $this->paramError('联系人ID不能为空');
        }

        try {
            $customerModel = new CustomerModel();

            // 获取联系人信息，检查客户权限
            $contact = Db::name('customer_contact')->find($contactId);
            if (!$contact || $contact['delete_time'] > 0) {
                return $this->error('联系人不存在', 404);
            }

            if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $contact['cid'], [
                'personal' => true,
                'department' => true,
                'shared' => true,
                'approval' => false,
                'creator' => true
            ])) {
                return $this->error('无权操作此客户', 403);
            }

            $result = $customerModel->updateCustomerContact($contactId, $param);

            if ($result) {
                return $this->success([], '更新联系人成功');
            } else {
                return $this->error('更新联系人失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('更新联系人失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 删除客户联系人
     */
    public function deleteContact()
    {
        $contactId = Request::param('id/d', 0);

        if (empty($contactId)) {
            return $this->paramError('联系人ID不能为空');
        }

        try {
            $customerModel = new CustomerModel();

            // 获取联系人信息，检查客户权限
            $contact = Db::name('customer_contact')->find($contactId);
            if (!$contact || $contact['delete_time'] > 0) {
                return $this->error('联系人不存在', 404);
            }

            if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $contact['cid'], [
                'personal' => true,
                'department' => true,
                'shared' => true,
                'approval' => false,
                'creator' => true
            ])) {
                return $this->error('无权操作此客户', 403);
            }

            $result = $customerModel->deleteCustomerContact($contactId);

            if ($result) {
                return $this->success([], '删除联系人成功');
            } else {
                return $this->error('删除联系人失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('删除联系人失败: ' . $e->getMessage(), 500);
        }
    }

    // ============================================
    // 客户跟进记录管理 API
    // ============================================

    /**
     * 添加客户跟进记录
     */
    public function addTrace()
    {
        $customerId = Request::param('customer_id/d', 0);
        $param = Request::param();

        if (empty($customerId)) {
            return $this->paramError('客户ID不能为空');
        }

        // 检查客户是否存在
        $customer = Db::name('customer')->where('id', $customerId)->where('delete_time', 0)->find();
        if (!$customer) {
            return $this->error('客户不存在', 404);
        }

        // 检查权限
        if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $customerId, [
            'personal' => true,
            'department' => true,
            'shared' => true,
            'approval' => false,
            'creator' => true
        ])) {
            return $this->error('无权操作此客户', 403);
        }

        try {
            $customerModel = new CustomerModel();
            $traceId = $customerModel->addCustomerTrace($customerId, $param);

            return $this->success(['id' => $traceId], '添加跟进记录成功');
        } catch (\Exception $e) {
            return $this->error('添加跟进记录失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 更新客户跟进记录
     */
    public function updateTrace()
    {
        $traceId = Request::param('id/d', 0);
        $param = Request::param();

        if (empty($traceId)) {
            return $this->paramError('跟进记录ID不能为空');
        }

        try {
            $customerModel = new CustomerModel();

            // 获取跟进记录信息，检查客户权限
            $trace = Db::name('customer_trace')->find($traceId);
            if (!$trace || $trace['delete_time'] > 0) {
                return $this->error('跟进记录不存在', 404);
            }

            if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $trace['cid'], [
                'personal' => true,
                'department' => true,
                'shared' => true,
                'approval' => false,
                'creator' => true
            ])) {
                return $this->error('无权操作此客户', 403);
            }

            $result = $customerModel->updateCustomerTrace($traceId, $param);

            if ($result) {
                return $this->success([], '更新跟进记录成功');
            } else {
                return $this->error('更新跟进记录失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('更新跟进记录失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 删除客户跟进记录
     */
    public function deleteTrace()
    {
        $traceId = Request::param('id/d', 0);

        if (empty($traceId)) {
            return $this->paramError('跟进记录ID不能为空');
        }

        try {
            $customerModel = new CustomerModel();

            // 获取跟进记录信息，检查客户权限
            $trace = Db::name('customer_trace')->find($traceId);
            if (!$trace || $trace['delete_time'] > 0) {
                return $this->error('跟进记录不存在', 404);
            }

            if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $trace['cid'], [
                'personal' => true,
                'department' => true,
                'shared' => true,
                'approval' => false,
                'creator' => true
            ])) {
                return $this->error('无权操作此客户', 403);
            }

            $result = $customerModel->deleteCustomerTrace($traceId);

            if ($result) {
                return $this->success([], '删除跟进记录成功');
            } else {
                return $this->error('删除跟进记录失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('删除跟进记录失败: ' . $e->getMessage(), 500);
        }
    }

    // ============================================
    // 客户机会线索管理 API
    // ============================================

    /**
     * 添加客户机会线索
     */
    public function addChance()
    {
        $customerId = Request::param('customer_id/d', 0);
        $param = Request::param();

        if (empty($customerId)) {
            return $this->paramError('客户ID不能为空');
        }

        // 检查客户是否存在
        $customer = Db::name('customer')->where('id', $customerId)->where('delete_time', 0)->find();
        if (!$customer) {
            return $this->error('客户不存在', 404);
        }

        // 检查权限
        if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $customerId, [
            'personal' => true,
            'department' => true,
            'shared' => true,
            'approval' => false,
            'creator' => true
        ])) {
            return $this->error('无权操作此客户', 403);
        }

        try {
            $customerModel = new CustomerModel();
            $chanceId = $customerModel->addCustomerChance($customerId, $param);

            return $this->success(['id' => $chanceId], '添加机会线索成功');
        } catch (\Exception $e) {
            return $this->error('添加机会线索失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 更新客户机会线索
     */
    public function updateChance()
    {
        $chanceId = Request::param('id/d', 0);
        $param = Request::param();

        if (empty($chanceId)) {
            return $this->paramError('机会线索ID不能为空');
        }

        try {
            $customerModel = new CustomerModel();

            // 获取机会线索信息，检查客户权限
            $chance = Db::name('customer_chance')->find($chanceId);
            if (!$chance || $chance['delete_time'] > 0) {
                return $this->error('机会线索不存在', 404);
            }

            if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $chance['customer_id'], [
                'personal' => true,
                'department' => true,
                'shared' => true,
                'approval' => false,
                'creator' => true
            ])) {
                return $this->error('无权操作此客户', 403);
            }

            $result = $customerModel->updateCustomerChance($chanceId, $param);

            if ($result) {
                return $this->success([], '更新机会线索成功');
            } else {
                return $this->error('更新机会线索失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('更新机会线索失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 删除客户机会线索
     */
    public function deleteChance()
    {
        $chanceId = Request::param('id/d', 0);

        if (empty($chanceId)) {
            return $this->paramError('机会线索ID不能为空');
        }

        try {
            $customerModel = new CustomerModel();

            // 获取机会线索信息，检查客户权限
            $chance = Db::name('customer_chance')->find($chanceId);
            if (!$chance || $chance['delete_time'] > 0) {
                return $this->error('机会线索不存在', 404);
            }

            if (!DataPermissionHelper::checkDataAccessEnhanced('customer', $chance['customer_id'], [
                'personal' => true,
                'department' => true,
                'shared' => true,
                'approval' => false,
                'creator' => true
            ])) {
                return $this->error('无权操作此客户', 403);
            }

            $result = $customerModel->deleteCustomerChance($chanceId);

            if ($result) {
                return $this->success([], '删除机会线索成功');
            } else {
                return $this->error('删除机会线索失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('删除机会线索失败: ' . $e->getMessage(), 500);
        }
    }
}
